package com.base.myproject.client.HR.Books;

import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseTreeStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.BaseTreeModel;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.data.TreeModel;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.ListView;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.Label;
/**
 * @author cxghiu410@gmail.com
 *	这个类用于实现规章制度的模块
 *	树的store查询还有待改进，现在只能查自己的文件，还不能查子树的文件
 */
public class TradeStatute extends BaseJDBCPanel {

	String treeClassNo = null; // 将当前树形结构中选中的类型文档id保存
	String treeTypeName = null; // 将当前树形结构中选中的类型文档name保存
	TreePanel<TreeModel> treepanel;

	String name = "";

	Button add = new Button("上传");
	Button refresh = new Button("刷新");
	
	TextField<String> searchName = new TextField<String>();
	
	Button search = new Button("搜索");

	Button save = new Button("保存");
	Dialog d = new Dialog();  //上传文件框
	Frame frame = new Frame("hr_Jsp/error.jsp");
	Dialog editRemark = new Dialog();

	public TradeStatute() {
		init();
	}

	public void init() {
		initWidget();
		registerMainStore(store);
		add.addListener(Events.Select, getListener());
		add.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.upload()));
		refresh.addListener(Events.Select, getListener());
		refresh.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.fresh()));
		search.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.find()));
		search.addListener(Events.OnClick, getListener());
		save.addListener(Events.Select, getListener());
	}

	public void complete() {
		super.complete();
	}

	ContentPanel colpanel;

	public void initWidget() {
		HorizontalPanel hp = new HorizontalPanel();
		hp.setSpacing(2);
		// Tools.setResize(hp, 1.00, 0.95);
		//ContentPanel cp = new ContentPanel();
		//cp.setHeaderVisible(false);
		hp.add(getTreePanel());

		colpanel = new ContentPanel();
		Tools.setResize(colpanel, 0.80, 0.95);

		ToolBar toolBar = new ToolBar();
		toolBar.add(add);
		toolBar.add(refresh);
		toolBar.add(searchName);
		toolBar.add(search);
		colpanel.setTopComponent(toolBar);
		colpanel.add(createView());
		hp.add(colpanel);

		//cp.add(hp);
		add(hp);
		
		editRemark.setHeading("编辑摘要");
		editRemark.setWidth(520);
		editRemark.setHeight(300);
		editRemark.setHideOnButtonClick(true);
		editRemark.getButtonById(Dialog.OK).addListener(Events.Select, getListener());
		editRemark.add(createForm());
		
		d.setHeading("上传文件");
		d.setWidth(520);
		d.setHeight(300);
		d.setHideOnButtonClick(true);
		d.getButtonById(Dialog.OK).addListener(Events.Select, getListener());
		DOM.setIntAttribute(frame.getElement(), "frameBorder", 0);
		frame.setWidth("500");
		frame.setHeight("300");
		d.add(frame);
	}

	BaseTreeStore<TreeModel> treeStore;

	private TreePanel<TreeModel> getTreePanel() {
		if (treepanel == null) {
			initTreePanel();
		}
		return treepanel;
	}

	private BaseTreeStore<TreeModel> getTreeStore() {
		if (treeStore == null) {
			initTreeStore();
		}
		return treeStore;
	}

	private BaseTreeStore<TreeModel> initTreeStore() {
		StoreInfo info = new StoreInfo();
		info
				.setSql("select icode,classNo,name from hr_docType where classNo is not null order by classNo asc");
		info.setTreesortcolumn("classNo");
		info.setKeyname(new String[] { "icode" });
		info.setTablename("hr_docType");
		treeStore = new BaseTreeStore<TreeModel>(info, false);
		treeStore.load();
		return treeStore;
	}

	String value;

	private void initTreePanel() {
		//treepanel.getStyle().set;
		treepanel = new TreePanel<TreeModel>(getTreeStore());
		treepanel.getStyle().setLeafIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.tree_file())); //改变树的图标
		Tools.setResize(treepanel, 0.20, 0.95);
		treepanel.setBorders(true);
		treepanel.setDisplayProperty("name");
		treepanel.setCheckStyle(CheckCascade.PARENTS);
		treepanel.setCheckNodes(CheckNodes.BOTH);
		treepanel.setCheckable(false);
		treepanel.setAutoLoad(true);
		treepanel.setCaching(true);

		treepanel.addListener(Events.OnClick,
				new Listener<TreePanelEvent<TreeModel>>() {
					public void handleEvent(TreePanelEvent<TreeModel> be) {
						if(be.getItem() != null) {
							if (be.getItem().getChildCount() == 0) {
								String id = be.getItem().get("classNo").toString();
								treeClassNo = id;
								//treeTypeName = be.getItem().get("name").toString();
								frame.setUrl("hr_Jsp/uploadfiles.jsp?classNo="
										+ treeClassNo);
								set_view(id);
							} else {
								frame.setUrl("hr_Jsp/error.jsp");
							}
						}
					}
				});
		treepanel.getSelectionModel().addSelectionChangedListener(
				new SelectionChangedListener<TreeModel>() {
					@Override
					public void selectionChanged(
							SelectionChangedEvent<TreeModel> se) {
						TreeModel md = se.getSelectedItem();
						if(md != null) {
							String columnName = md.get("name");
							treeClassNo = md.get("classNo");
							treeTypeName = columnName;
							colpanel.setHeading("您当前的位置  > " + columnName);
						}
					}

				});

		Menu contextMenu = new Menu();

		MenuItem insert = new MenuItem();
		insert.setText("添加栏目");
		insert.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.addrecord()));
		insert.addSelectionListener(new SelectionListener<MenuEvent>() {
			public void componentSelected(MenuEvent ce) {
				final TreeModel model = treepanel.getSelectionModel()
						.getSelectedItem();
				if (model != null) {
					final MessageBox box = MessageBox.prompt("添加栏目", "栏目名称:");
					box.addCallback(new Listener<MessageBoxEvent>() {
						public void handleEvent(MessageBoxEvent be) {
							Button clicked = be.getButtonClicked();
							if (clicked.getItemId().equals(Dialog.OK)) {
								name = be.getValue();
								selectChileTreeCount(model);
							}

						}
					});
				}
			}
		});
		contextMenu.add(insert);

		MenuItem remove = new MenuItem();
		remove.setText("删除栏目");
		remove.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.deleterecord()));
		remove.addSelectionListener(new SelectionListener<MenuEvent>() {
			public void componentSelected(MenuEvent ce) {
				List<TreeModel> selected = treepanel.getSelectionModel().getSelectedItems();
				String sql_center = "select count(*) as i from hr_docCenter where classNo like '"
						+ treeClassNo + "%'";
				selectFileExit(sql_center, selected);
			}
		});
		contextMenu.add(remove);
		treepanel.setContextMenu(contextMenu);
	}

	private void set_view(String id) {
		StoreInfo info2 = new StoreInfo();
		info2.setTablename("hr_docCenter");
		info2.setKeyname(new String[] { "icode" });
		String where = " where 1=1 and ";
		if (id.length() < 5) {
			where = where + " classNo like '" + id + "%25'";
		} else {
			where = where + " classNo = '" + id + "'";
		}
		info2.setSql("select * from hr_docCenter " + where);// 这里sql的linke
		// %% 有问题
		store.setStoreinfo(info2);
		store.reload();
	}

	BaseStore<BusiObject> store = null;
	ListView<BusiObject> view = null;

	public ContentPanel createView() {
		final ContentPanel panel = new ContentPanel();
		panel.setHeaderVisible(false);
		panel.setFrame(true);
		panel.setId("files-view");

		panel.setBodyBorder(false);

		view = new ListView<BusiObject>() {
			@Override
			protected BusiObject prepareData(BusiObject model) {
				return model;
			}
		};

		view.setTemplate(getTemplate());
		view.setStore(createStore());

		view.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
		view.setItemSelector("div.thumb-wrap");
		view.getSelectionModel().addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent<BusiObject>>() {
					public void handleEvent(SelectionChangedEvent<BusiObject> be) {
						if (store.indexOf(view.getSelectionModel()
								.getSelectedItem()) >= 0)
							store.gotorow(store.indexOf(view
									.getSelectionModel().getSelectedItem()));
					}
				});

		Menu contextMenu = new Menu();
		MenuItem remove = new MenuItem();
		remove.setText("删除文件");
		remove.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.deleterecord()));
		remove.addSelectionListener(new SelectionListener<MenuEvent>() {
			public void componentSelected(MenuEvent ce) {
				if (store.getCurcowindex() >= 0) {
					store.remove(store.getAt(store.getCurcowindex()));
					store.trySave();
					store.reload();
				}
				
				String url = "../hr_Jsp/deleteFile.jsp?path=" + store.getValue("path");
		        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
		        builder.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		        String data = "";
		        try {
					builder.sendRequest(data, new RequestCallback() {
					    public void onError(Request request, Throwable exception) {
					        MessageBox.alert("Error", "error save colum:" + exception.getMessage(), null);
					    }

					    @SuppressWarnings("unchecked")
					    public void onResponseReceived(Request request, Response response) {
					    	
					    }
					       
					});
				} catch (RequestException e) {
					e.printStackTrace();
				}
			}
		});
		
		MenuItem edit = new MenuItem();
		edit.setText("编辑摘要");
		edit.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.edit()));
		edit.addSelectionListener(new SelectionListener<MenuEvent>() {
			public void componentSelected(MenuEvent ce) {
				editRemark.show();
			}
		});
		
		contextMenu.add(remove);
		contextMenu.add(edit);
		view.setContextMenu(contextMenu);

		panel.add(view);
		
		view.setSize(780, 395); panel.setSize(780, 395);
		 
		Tools.setResize(view, 0.79, 0.80);
		Tools.setResize(panel, 0.80, 0.95);

		return panel;
	}

	public BaseStore<BusiObject> createStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("fileName");
		type.getField("fileName").setType(String.class);
		type.addField("path");
		type.getField("path").setType(String.class);
		type.addField("remark");
		type.getField("remark").setType(String.class);
		type.addField("type");
		type.getField("type").setType(String.class);
		type.addField("upload");
		type.getField("upload").setType(String.class);
		type.addField("classNo");
		type.getField("classNo").setType(String.class);
		type.addField("fileSize");
		type.getField("fileSize").setType(String.class);
		type.addField("showPathUrl");
		type.getField("showPathUrl").setType(String.class);
		type.addField("showFileName");
		type.getField("showFileName").setType(String.class);
		type.addField("showRemark");
		type.getField("showRemark").setType(String.class);

		StoreInfo info = new StoreInfo();
		info.setTablename("hr_docCenter");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from hr_docCenter where 1=0");
		store = new BaseStore<BusiObject>(type, info);
		return store;
	}

	private native String getTemplate() /*-{
		return ['<tpl  for=".">', 
		'<div class="thumb-wrap" id="sss" style="border: 1px solid white;float:left;">',
		'<div class="thumb" align="center"><a href="{path}" target="_blank"  title="{fileName}"><img style="width:50px;height:50px;border:5px double #eee;margin: 3px 2px 2px 3px" src="{showPathUrl}"></a></div>', 
		'<span class="x-editable" style="float:left" >{showFileName}</span>',
		'<span class="x-editable">&nbsp;</span></div>', 
		'</tpl>',
		'<div class="x-clear"></div>'].join("");
	}-*/;
	
	BaseFormPanel form  =null;
	TextArea C_num4;
	BaseFormPanel createForm() {
		BaseFormPanel form = new BaseFormPanel(store);
		TableLayout tl = new TableLayout(2);

		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);
		form.setLayout(tl);
		form.setHeaderVisible(false);
		form.add(new Label("文件名:"), td);
		TextField<String> fileName = new TextField<String>();
		fileName.setName("fileName");
		fileName.setWidth(430);
		fileName.setReadOnly(true);
		form.add(fileName, td);

		form.add(new Label("摘要:"), td);
		C_num4 = new TextArea();
		C_num4.setHeight(178);
		C_num4.setWidth(430);

		C_num4.setName("remark");
		form.add(C_num4, td);
		
		form.inited();
		return form;
	}

	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							if (be.getSource().equals(add)) {
								d.show();
							} else if (be.getSource().equals(refresh)) {
								store.reload();
							} else if (be.getSource().equals(
									d.getButtonById(Dialog.OK))) {
								store.reload();
							}  else if (be.getSource().equals(
									editRemark.getButtonById(Dialog.OK))) {
								String oldValue = C_num4.getRawValue();
								String newValue = "";
								String br = "&#13;";
								String[] oldArray = oldValue.split("\\r\\n");
								for(String old : oldArray) {
									int sum = 0;
									if(old.length() > 40) {
										for(int i=0;i<(old.length() / 40);i++) {
											sum = (i+1)*40;
											newValue = newValue + old.substring(sum-40, sum) + br;
										}
										newValue = newValue + old.substring(sum);
									} else {
										newValue = newValue + old;
									}
									newValue = newValue + br;
								}
								
								String sql = "update hr_docCenter set remark = '" + oldValue + "',showRemark = '" + newValue + "' where path = '" + store.getValue("path") + "'";
								saveRemark(sql);
							}
							else if (be.getSource().equals(save)) {
								store.trySave(store.getCurcowindex());
							}
						} else if (be.getType() == Events.OnClick) {
							if (be.getSource().equals(search)) {
								to_search();
							}
						}
					}
				} finally {
					sync--;
				}
			}
		};
		return defaultlistener;
	}
	
	private void to_search() {
		String searchValue = searchName.getRawValue();
		String[] searchArray = searchValue.split("\\s");
		String wheres = store.getStoreinfo().getSql();
		String condition = "";
		for(int i=0;i<searchArray.length;i++) {
			String value = searchArray[i];
			if(value.equals("")) continue;
			condition = " and fileName like '%25" + value + "%25'";
			wheres = wheres + condition;
		}
		store.getStoreinfo().setSql(wheres);
		store.reload();
	}

	public void setStore(BaseStore<BusiObject> store) {
		this.store = store;
	}

	// 还有同步没实现
	public void selectChileTreeCount(final TreeModel model) {
		if (treeClassNo == null) {
			MessageBox.alert("警告", "请先选择一个分部门！", null);
		} else {
			String sql = "select count(*) as i, max(classNo) as d from hr_docType where classNo like '"
					+ treeClassNo + "__'";
			final GreetingServiceAsync greetingService = GWT
					.create(com.base.myproject.client.tools.GreetingService.class);
			greetingService.getDataSet(sql, new AsyncCallback<DataSet>() {
				@Override
				public void onFailure(Throwable caught) {
				}

				@Override
				public void onSuccess(DataSet result) {
					
					 int count = Integer.parseInt(result.getValue(0, "i")) + 1;
					 if (count < 10) {
						 value = treeClassNo + "0" + count; }
					 else {
						 value = treeClassNo + count; 
					}
					 
					if (result.getValue(0, "i").equals("0")) {
						value = treeClassNo + "01";
					} else {
						String subNumber = result.getValue(0, "d");
						subNumber = subNumber.substring(subNumber.length() - 2);
						count = Integer.parseInt(subNumber) + 1;
						if (count < 10) {
							value = treeClassNo + "0" + count;
						} else {
							value = treeClassNo + count;
						}
					}

					String sql = "insert into hr_docType (classNo, name) values ('"
							+ value + "', '" + name + "')";
					operationChileTree(sql, "添加成功");
					TreeModel child = new BaseTreeModel();
					child.set("name", name);
					child.set("classNo", value);
					treeStore.add(model, child, false);
					treepanel.setExpanded(model, true);
				}
			});

		}
	}

	public void selectFileExit(final String sql, final List<TreeModel> selected) {
		if (treeClassNo == null) {
			MessageBox.alert("警告", "请先选择一个分部门！", null);
		} else {
			final GreetingServiceAsync greetingService = GWT
					.create(com.base.myproject.client.tools.GreetingService.class);
			greetingService.getDataSet(sql, new AsyncCallback<DataSet>() {
				@Override
				public void onFailure(Throwable caught) {
				}

				@Override
				public void onSuccess(DataSet result) {
					if (!result.getValue(0, "i").equals("0")) {
						String tip = treeTypeName + "栏目还存在上传文件，请将您要删除的栏目"
								+ treeTypeName + "及其子目录下的上传文件删除，再进行该栏目的删除，谢谢!";
						MessageBox.alert("警告",
								tip, null);
					} else {
						for(TreeModel model : selected) {
							treeStore.remove(model);
						}
						String sql = "delete from hr_docType where classNo like '"
								+ treeClassNo + "%'";
						operationChileTree(sql, "删除成功");
					}
				}
			});
		}
	}

	public boolean operationChileTree(String sql, final String success) {
		CommandSyncsql csql = new CommandSyncsql();// 执行sql命令
		String delsql = sql;
		csql.getV().add(delsql);
		if (csql.getV().size() <= 0) {
			return false;
		} else {
			CommandSyncContainer list = new CommandSyncContainer();// 可以添加的命令
			list.add(csql);

			GreetingServiceAsync greetingService = GWT
					.create(GreetingService.class);
			greetingService.SendCommandSync(list,
					new AsyncCallback<CommandSyncReturnObject>() {
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("错误", "网络连接失败", null);
						}

						@Override
						public void onSuccess(CommandSyncReturnObject result) {
							if (result.isB()) {
								Info.display("提示信息", success);
							} else {
								MessageBox.alert("错误", "错误，错误代码"
										+ result.getMessage(), null);

							}
						}
					});
		}
		return true;
	}
	
	public boolean saveRemark(String sql) {
		CommandSyncsql csql = new CommandSyncsql();// 执行sql命令
		String delsql = sql;
		csql.getV().add(delsql);
		if (csql.getV().size() <= 0) {
			return false;
		} else {
			CommandSyncContainer list = new CommandSyncContainer();// 可以添加的命令
			list.add(csql);

			GreetingServiceAsync greetingService = GWT
					.create(GreetingService.class);
			greetingService.SendCommandSync(list,
					new AsyncCallback<CommandSyncReturnObject>() {
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("错误", "网络连接失败", null);
						}

						@Override
						public void onSuccess(CommandSyncReturnObject result) {
							if (result.isB()) {
								Info.display("提示信息", "摘要保存成功");
								store.reload();
							} else {
								MessageBox.alert("错误", "错误，错误代码"
										+ result.getMessage(), null);

							}
						}
					});
		}
		return true;
	}
}
